package com.fengyi.library.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 负载均衡控制器，用于测试负载均衡功能
 */
@RestController
@RequestMapping("/api/lb-test")
public class LoadBalancerController {

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 返回当前服务实例的端口号
     */
    @GetMapping
    public Map<String, String> getLoadBalancerInfo() {
        Map<String, String> result = new HashMap<>();
        result.put("currentPort", serverPort);
        result.put("message", "当前服务运行在端口: " + serverPort);
        
        // 输出当前端口号到控制台
        System.out.println("********************************************");
        System.out.println("* 负载均衡测试 - 端口 " + serverPort + " 收到请求 *");
        System.out.println("********************************************");
        
        // 通过负载均衡访问服务信息API
        try {
            // Make a real load-balanced call to the service-info endpoint of one of the instances
            // The service name "cloud-library-service" should be resolved by the load balancer
            // to one of the registered instances (e.g., on port 8000 or 8001).
            ResponseEntity<Map<String, String>> responseEntity = restTemplate.exchange(
                    "http://cloud-library-service/api/service-info",
                    HttpMethod.GET,
                    null,
                    new ParameterizedTypeReference<Map<String, String>>() {}
            );

            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                Map<String, String> responseBody = responseEntity.getBody();
                if (responseBody != null) {
                    result.put("loadBalancedPort", responseBody.getOrDefault("port", "N/A"));
                    result.put("loadBalancedInstance", responseBody.getOrDefault("instance", "N/A"));
                } else {
                    result.put("loadBalancedPort", "Error");
                    result.put("loadBalancedInstance", "Response body was null");
                    result.put("error", "负载均衡请求成功但响应体为空");
                }
            } else {
                result.put("loadBalancedPort", "Error");
                result.put("loadBalancedInstance", "Status: " + responseEntity.getStatusCode());
                result.put("error", "负载均衡请求失败，状态码: " + responseEntity.getStatusCode());
            }
        } catch (Exception e) {
            result.put("loadBalancedPort", "Error");
            result.put("loadBalancedInstance", "Exception: " + e.getClass().getSimpleName());
            result.put("error", "负载均衡请求异常: " + e.getMessage());
        }
        
        return result;
    }
} 